//
// service统一出口
import HYRequest from './request/request'
import { BASE_URL, TIME_OUT } from './request/config'
import { strage, Base64 } from '@/utils/index'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const instance = axios.create({ baseURL: BASE_URL, timeout: TIME_OUT })
instance.interceptors.request.use((config: any) => {
  // 携带token的拦截
  const token = strage.getCache('lbs_tk')
  if (token) {
    config.headers.signature = token
  }
  return config
})

// token过期无感重新请求
function afreshRequest(config: object, resolve: any, reject: any) {
  instance
    .request<any>(config)
    .then(res => {
      resolve(res)
    })
    .catch(err => {
      resolve(err)
      // 将showLoading设置true, 这样不会影响下一个请求
    })
}
//请求实例
const hyRequest = new HYRequest({
  baseURL: BASE_URL,
  timeout: TIME_OUT,
  interceptors: {
    requestInterceptor: (config: any) => {
      // 携带token的拦截
      // const token = strage.getCache('lbs_tk')
      // if (token) {
      //   config.headers.signature = token
      // }
      // //等待刷新token
      // if (isRefreshToken && config.url !== 'sso/keepSignature') {
      //   return new Promise((resolve, reject) => {
      //     const timer: number = window.setInterval(() => {
      //       if (isRefreshToken) {
      //         return
      //       } else {
      //         window.clearInterval(timer)
      //       }
      //       resolve(config)
      //     }, 200)
      //   })
      // } else {
      //   return config
      // }
      return config
    },
    requestInterceptorCatch: err => {
      return err
    },
    responseInterceptor: res => {
      console.log(res, 'res')
      if (res.data.state === 204) {
        ElMessage.error(res.data.msg)
      }
      return res
    },
    responseInterceptorCatch: err => {
      return err
    },
  },
})

export default hyRequest
